<?php
// +----------------------------------------------------------------------
// | huicmf [ huicmf快速开发框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2024 https://xiaohuihui.cc All rights reserved.
// +----------------------------------------------------------------------
// | Author: 小灰灰 <762229008@qq.com>
// +----------------------------------------------------------------------
// | Info:
// +----------------------------------------------------------------------

namespace app\common\library;

use app\index\controller\BaseController;
use think\facade\Db;

class Html extends BaseController
{

//数据
    protected $data = [];

    //错误信息
    protected $error = null;

    protected function initialize()
    {
        parent::initialize();

        // 取消模板缓存
        $this->view->config(['tpl_cache' => false, 'display_cache' => false]);

        // 非开发者模式下,屏蔽错误
        if ( ! $this->app->isDebug()) {
            // 屏蔽掉notice错误
            error_reporting(E_ALL ^ E_NOTICE);
        }
    }

    /**
     * 获取错误提示
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 重置整站URL
     */
    public static function clearUrl()
    {
        // 栏目URL
        Db::name('category')->where(['status' => 1])->where('model_id', '>', 0)->update(['url' => '']);

        // 内容URL
        Db::name('content')->where('url', '<>', '')->update(['url' => '']);

        @unlink(public_path().'index.html');
    }

    /**
     * 生成整站url规则
     */
    public static function buildUrl()
    {
        // 获取栏目与内容规则
        $columnUrl  = Db::name('config')->where(['name' => 'html_column_rules'])->find();
        $columnUrl  = $columnUrl['value'];
        $contentUrl = Db::name('config')->where(['name' => 'html_content_rules'])->find();
        $contentUrl = $contentUrl['value'];

        // 栏目URL
        $categorys = Db::name('category')->where(['status' => 1])->select()->toArray();
        $newCate   = [];
        foreach ($categorys as $key => $category) {
            if ($category['model_id'] <= 0) {
                continue;
            }
            //需要替换的标签
            $replace_l = [];
            //替换的内容
            $replace_r = [];
            // 父栏目
            $catdir = '';
            if (strstr($columnUrl, '[catdir]')) {
                //获取当前栏目父栏目
                $catdir      = $category['pid'] ? Db::name('category')->where('id', '=',
                    $category['pid'])->value('dirname') : '';
                $replace_r[] = $catdir;
                $replace_l[] = '[catdir]';
            }
            // 栏目目录
            if (strstr($columnUrl, '[list]')) {
                $replace_l[] = '[list]';
                $replace_r[] = $category['dirname'];
            }
            //标签替换
            $url = str_replace($replace_l, $replace_r, $columnUrl);
            $url = str_replace(["//"], '/', $url);
            $url = explode("|", $url);
            // 多语言的处理
            $url[0] = self::getRootPath().dirname($url[0]).'/';
            $url[0] = str_replace(["//", "\\"], '/', $url[0]);
            Db::name('category')->where('id', '=', $category['id'])->update(['url' => $url[0]]);
            $category['parent_dir']   = $catdir;
            $newCate[$category['id']] = $category;
        }

        // 内容URL
        $model = Db::name('models')->where(['status' => 1])->select();
        foreach ($model as $key => $value) {
            $c   = '\app\common\model\Content';
            $obj = (new $c)->where(['status' => 1])->select();
            if ( ! empty($obj)) {
                foreach ($obj as $k => $v) {
                    $replace_l = []; //需要替换的标签
                    $replace_r = []; //替换的内容

                    // 父栏目
                    if (strstr($contentUrl, '[catdir]')) {
                        //获取当前栏目父栏目
                        $replace_r[] = isset($newCate[$v['category_id']]) && $newCate[$v['category_id']]['parent_dir'] ? $newCate[$v['category_id']]['parent_dir'] : '';
                        $replace_l[] = '[catdir]';
                    }
                    // 栏目目录
                    if (strstr($contentUrl, '[list]')) {
                        $replace_l[] = '[list]';
                        $replace_r[] = isset($newCate[$v['category_id']]) ? $newCate[$v['category_id']]['dirname'] : '';
                    }
                    //年份
                    if (strstr($contentUrl, '[year]')) {
                        $replace_l[] = '[year]';
                        $replace_r[] = date('Y', $v['publish_time'] ?? $v['create_time']);
                    }
                    //月份
                    if (strstr($contentUrl, '[month]')) {
                        $replace_l[] = '[month]';
                        $replace_r[] = date('m', $v['publish_time'] ?? $v['create_time']);
                    }
                    //日期
                    if (strstr($contentUrl, '[day]')) {
                        $replace_l[] = '[day]';
                        $replace_r[] = date('d', $v['publish_time'] ?? $v['create_time']);
                    }
                    //文件名，如果有自定义文件名则使用自定义文件名，否则默认使用当前内容ID
                    if ( ! empty($v['diyname'])) {
                        $replace_l[] = '[id]';
                        $replace_r[] = $v['diyname'];
                    } else {
                        $replace_l[] = '[id]';
                        $replace_r[] = $v['id'];
                    }
                    //标签替换
                    $urlrule    = str_replace($replace_l, $replace_r, $contentUrl);
                    $urlrule    = str_replace(["//"], '/', $urlrule);
                    $urlrule    = explode("|", $urlrule);
                    $urlrule[0] = self::getRootPath($urlrule[0]);
                    $urlrule[0] = str_replace(array("//", "\\"), '/', $urlrule[0]);
                    (new $c)->where(['id' => $v['id']])->save(['url' => $urlrule[0]]);
                }
            }
        }
    }

    /**
     * 获取生成的根路径
     *
     * @param string $file
     *
     * @return string
     */
    public static function getRootPath(string $file = '')
    {
        $html_dir = get_config('html_dir');

        return ($html_dir ? '/'.$html_dir.'/' : '/').$file;
    }

}
